package concurrency;

/**
 * volatile保证共享变量的可见性
 * 不加volatile的话第一个线程无法获取到第二个线程改变后的flag值，无法跳出死循环，后续操作不会执行
 */
public class VolatileDemo {

    private static volatile boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("waiting for data");
                while (!flag) {
                }
                System.out.println("=== data success ===");
            }
        }).start();

        Thread.sleep(2000);

        new Thread(() -> {
            prepareData();
        }).start();
    }

    private static void prepareData() {
        System.out.println("prepare data");
        flag = true;
        System.out.println("prepare data end");
    }
}
